﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using pTools.cMethods;
using DevExpress.XtraGrid.Views.Grid;
using Flurl.Http;
using Flurl;
using Entity.DbEntity;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Configuration;

namespace pTools.TuQiangPrint
{
    public partial class PrintedBarListForm : DevExpress.XtraEditors.XtraForm
    {
        DBHelper db = new DBHelper();
        HttpAgreement http = new HttpAgreement();

        public PrintedBarListForm()
        {
            InitializeComponent();
        }

        List<BarCodeListModel> ds;

        private void PrintedBarListForm_Load(object sender, EventArgs e)
        {
            RefreshList();
        }

        void RefreshList()
        {
            var sql_temp = "select * from bar_ProductBarCode_info where createuser = '{0}' and isInitial = 'N' and status = 'Y' and barStatus = 'need-in';";
            var sql = string.Format(sql_temp, CommonMethods.userCode);

            ds = CommonMethods.ConvertTo<BarCodeListModel>(db.getData(sql));

            grid_BarCodeList.DataSource = ds;
            grid_BarCodeList.RefreshDataSource();
        }

        private void barBtn_InStorage_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var selected_Indexes = ((GridView)grid_BarCodeList.MainView).GetSelectedRows();

            var selectedModels = ds.Where((element, index) => selected_Indexes.Contains(index)).ToList();

            var subModels = new List<DbSubBarCode>() { };

            foreach (var model in selectedModels)
            {
                var barCode = model.barCode;

                var sql_temp = "select * from [bar_ProductBarCode_Sub_info] where barCode = '{0}';";
                var sql = string.Format(sql_temp, barCode);

                var dt = db.getData(sql);

                var subList = CommonMethods.ConvertTo<DbSubBarCode>(dt);

                subModels.AddRange(subList);
            }

            //根据存货编码，颜色，商标 汇总相同存货
            var items = subModels.GroupBy(m => new { m.proCode, m.color, m.trademark })
                .Select(g => new
                {
                    proCode = g.Key.proCode,
                    proName = g.First().proName,
                    color = g.Key.color,
                    trademark = g.Key.trademark,
                    total = g.ToList().Sum(s => s.number),
                    cu_baozhuang = g.ToList().First().cu_baozhuang,
                    cu_guohao = g.ToList().First().cu_guohao
                });


            var sys_obj = new JObject();

            sys_obj["sAccID"] = ConfigurationManager.AppSettings["sAccID"];
            sys_obj["sYear"] = CommonMethods.GetYear();
            sys_obj["sDate"] = CommonMethods.GetDateStr();
            sys_obj["sServer"] = ConfigurationManager.AppSettings["sServer"];
            sys_obj["sUserID"] = ConfigurationManager.AppSettings["sUserID"];
            sys_obj["sPassword"] = ConfigurationManager.AppSettings["sPassword"];

            var head_obj = new JObject();

            head_obj["cwhcode"] = GetInitWarehouse();
            //head_obj["cwhcode"] = "1";
            //head_obj["ddate"] = CommonMethods.GetDateStr();
            head_obj["ddate"] = CommonMethods.GetDateStr();
            head_obj["cmaker"] = CommonMethods.userName;
            head_obj["csource"] = "库存";
            // 部门取条码中的默认部门
            head_obj["cdepcode"] = GetDefaultDeptCode();
            head_obj["vt_id"] = "63";


            var list_arr = new JArray();

            var rowCount = 1;
            foreach (var item in items)
            {
                var listObj = new JObject();

                listObj["irowno"] = rowCount;
                listObj["cinvcode"] = item.proCode;
                listObj["cinvname"] = item.proName;
                listObj["iquantity"] = item.total;

                listObj["cfree1"] = item.color;
                //listObj["cfree2"] = "锅号";
                listObj["cfree2"] = item.cu_guohao;
                listObj["cfree3"] = item.trademark;
                //listObj["cfree4"] = "装箱";
                listObj["cfree4"] = item.cu_baozhuang;

                list_arr.Add(listObj);
                rowCount++;
            }

            //var l_obj1 = new JObject();
            //l_obj1["irowno"] = "1";
            //l_obj1["cinvcode"] = "11010001";
            //l_obj1["cinvname"] = "蓝色PVC夹网400面";
            //l_obj1["inum"] = "2";
            //l_obj1["iquantity"] = "42";
            //// cfree1 颜色 cfree2 锅号 cfree3 商标 cfree4 存放形式
            //l_obj1["cfree1"] = "free1";
            //l_obj1["cfree2"] = "free2";
            //l_obj1["cfree3"] = "free3";
            //l_obj1["cfree4"] = "free4";


            //var l_obj2 = new JObject();
            //l_obj2["irowno"] = "2";
            //l_obj2["cinvcode"] = "11010001";
            //l_obj2["cinvname"] = "蓝色PVC夹网400面";
            //l_obj2["inum"] = "2";
            //l_obj2["iquantity"] = "42";

            //l_obj2["cfree1"] = "free1";
            //l_obj2["cfree2"] = "free2";
            //l_obj2["cfree3"] = "free3";
            //l_obj2["cfree4"] = "free4";


            //list_arr.Add(l_obj1);
            //list_arr.Add(l_obj2);

            var queryObj = new JObject();

            queryObj["System"] = sys_obj;
            queryObj["Head"] = head_obj;
            queryObj["List"] = list_arr;

            var jsonStr = JsonConvert.SerializeObject(queryObj);

            var url = ConfigurationManager.AppSettings["protocolAddress"];
            url += "ProductIn";
            //string rsl = url.PostStringAsync(url).ReceiveString();

            var rslStr = http.HttpPost(url, jsonStr);

            var rsl = JsonConvert.DeserializeObject<ReturnResult>(rslStr);

            if (rsl.Result)
            {


                var mCode = DateTime.Now.ToString("yyyyMMddHHmmss");

                // 添加出入库记录
                var totalSql = "";

                // 主表

                var mainSql_template = @"INSERT INTO [bar_BarEntryRecords_main] 
      (happenDate,wareHouse,maker,createtime,createuser,[status], deptCode, outOrderCode, memo, isForm,inOutType, baseCode,isBlue, mCode)
VALUES('{0}',       '{1}',      '{2}',  '{3}',       '{4}',       '{5}',     '{6}',       '{7}',          '{8}',  '{9}',   '{10}',      '{11}',    '{12}', '{13}'); ";
                var mainsql = string.Format(mainSql_template,
                    CommonMethods.GetDateStr(), // 0
                    GetInitWarehouse(), // 1
                    CommonMethods.userName, // 2
                    CommonMethods.GetTimeStr(), // 3
                    CommonMethods.userCode, // 4

                    "needAudit", // 5
                    GetDefaultDeptCode(), // 6
                    rsl.Data.ToString(), // 7
                    "生产入库", // 8
                    "PC", // 9

                    "piw", // 10
                    CommonMethods.baseCode, // 11
                    "1", //12
                    mCode// 13
                    );

                totalSql += mainsql;

                // 子表

                foreach (var index in ((GridView)grid_BarCodeList.MainView).GetSelectedRows())
                {
                    var m = ds[index];
                    var childSql_template = @"INSERT INTO [bar_BarEntryRecords_list]
      (barCode,num,status,createtime,createuser,inOutType, mCode)               
VALUES('{0}',    '{1}','{2}',   '{3}',       '{4}',       '{5}', '{6}'); ";
                    var childSql = string.Format(childSql_template,
                        m.barCode, // 0
                        m.number, // 1
                        "Y", // 2
                        CommonMethods.GetTimeStr(), // 3
                        CommonMethods.userCode, // 4
                        "piw", // 5
                        mCode// 6
                        );

                    totalSql += childSql;
                }

                db.TransUpdate(new List<string> { totalSql });

                // 将条码状态变为"待出库"，并且刷新界面

                var sql_temp = "update bar_ProductBarCode_info set barStatus = 'need-out' where barCode in ('{0}')";
                var barCodes_Str = string.Join("','", selectedModels.Select(m => m.barCode));
                var sql = string.Format(sql_temp, barCodes_Str);

                var result = db.UpdateData(sql);

                RefreshList();

                XtraMessageBox.Show("入库成功！" + Environment.NewLine + "产成品入库单编码：" + rsl.Data);
            }
            else
            {
                XtraMessageBox.Show(rsl.Message);
            }

        }

        string GetDefaultDeptCode()
        {
            var sql = "select * from sys_parameters_info where parCode = 'all_Dept_Style'";
            var dt = db.getData(sql);

            return dt.Rows[0]["parValue"].ToString();
        }

        // 获取默认仓库
        string GetInitWarehouse()
        {
            var sql = "select * from [sys_parameters_info] where parCode = 'InitWarehouseCode'; ";
            var dt = db.getData(sql);
            return dt.Rows[0]["parValue"].ToString();
        }

        private void btn_closeWindow_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.Close();
        }

        private void barItem_refresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            RefreshList();
        }
    }
}